const Role = require('@/models/role.models')
const { createResponse, createErrorResponse } = require('@/utils/tool')

/**
 * 创建角色
 * @param {*} options 
 * @param {*} options.name 角色名
 * @param {*} options.description 描述
 * @returns 响应信息
 */
async function createRole(options) {
  try {
    let { name, description } = options
    // 检查是否已经存在相同的角色
    const existingRole = await Role.findOne({
      where: {
        name,
        deletedAt: null
      }
    });
    if (existingRole) {
      return createResponse({ code: 400, message: "角色已存在" })
    }
    const role = await Role.create({
      name,
      description
    })
    return createResponse({ data: role, message: "创建角色成功" })
  } catch (error) {
    return createErrorResponse(error)
  }
}

/**
 * 通过ID查询角色
 * @param {*} roleId 角色ID
 */
async function getRoleById(roleId) {
  try {
    const role = await Role.findByPk(roleId);
    if (role) {
      const roleInfo = role.toJSON()
      return createResponse({ message: "请求成功", code: 200, data: { roleInfo } })
    } else {
      return createResponse({ message: "角色不存在", code: 401 })
    }
  } catch (error) {
    return createErrorResponse(error)
  }
}

/**
 * 查询所有角色数据
 * @param {*} order 排序字段 ASC/DESC
 * @returns 
 */
async function getAllRoles(order) {
  try {
    const roles = await Role.findAll({
      order: [['createdAt', order ?? 'ASC']],
      where: {
        deletedAt: null
      }
    });
    const list = roles.map(role => role.toJSON());
    return createResponse({ message: "请求成功", code: 200, data: { list, total: roles.length } })
  } catch (error) {
    return createErrorResponse(error)
  }
}

/**
 * 分页查询角色
 * @param {*} page 页码
 * @param {*} pageSize 数量
 * @param {*} order 排序字段 ASC/DESC
 * @returns 
 */
async function getPaginatedRoles(page = 1, pageSize = 10, order) {
  try {
    const offset = (page - 1) * pageSize;
    const limit = Number(pageSize);
    const roles = await Role.findAndCountAll({
      offset,
      limit,
      order: [['createdAt', order ?? 'ASC']],
      where: {
        deletedAt: null
      }
    });
    console.log('roles :>> ', roles);
    let list = roles.rows.map(role => {
      return role.toJSON()
    });
    return createResponse({ message: "请求成功", code: 200, data: { list, total: roles.count } })
  } catch (error) {
    return createErrorResponse(error)
  }
}

/**
 * 更改角色信息
 * @param {*} roleId 角色ID
 * @param {*} updates 更新的信息
 */
async function updataRole(roleId, updates) {
  try {
    const role = await Role.findByPk(roleId);
    if (role) {
      Object.assign(role, updates);
      await role.save();
      return createResponse({ message: "更新成功", code: 200, data: role.toJSON() })
    } else {
      return createResponse({ message: "角色不存在", code: 401, data: {} })
    }
  } catch (error) {
    return createErrorResponse(error)
  }
}

/**
 * 通过ID删除
 * @param {*} roleId 角色ID
 */
async function deleteRole(roleId) {
  try {
    const role = await Role.findByPk(roleId);
    if (role) {
      await role.destroy(); // 假删除
      // await user.destroy({ force: true }); // 强制删除
      return createResponse({ message: "删除成功", code: 200 })
    } else {
      return createResponse({ message: "角色不存在", code: 401 })
    }
  } catch (error) {
    return createErrorResponse(error)
  }
}

module.exports = {
  createRole,
  getRoleById,
  getAllRoles,
  getPaginatedRoles,
  updataRole,
  deleteRole
}